package com.mall.file.Controller;

import com.mall.file.ceph.FileHandler;
import com.mall.util.RespResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @description:
 * @author: ljr
 * @time: 2021/9/5 11:18
 */
@RestController
@RequestMapping("/file")
public class FileController {

    @Resource
    private FileHandler fileHandler;


    @PostMapping(value = "/upload")
    public RespResult upload(MultipartFile file) throws IOException {
        fileHandler.upload(file.getName(), file.getBytes());
        return RespResult.ok();
    }

    @GetMapping(value = "/download/{fileName}")
    public RespResult download(@PathVariable String fileName,
                               HttpServletResponse response) throws IOException {
        byte[] buffer = fileHandler.downLoad(fileName);
        ServletOutputStream outputStream = response.getOutputStream();
        outputStream.write(buffer);
        outputStream.flush();
        outputStream.close();
        return RespResult.ok();
    }
}
